from PySide6.QtCharts import QChart, QChartView, QPieSeries, QBarSeries, QBarSet, QBarCategoryAxis, QValueAxis
from PySide6.QtCore import Qt
from PySide6.QtGui import QPainter

class TaskStatsChart:
    @staticmethod
    def create_pie_chart(task):
        """创建饼图"""
        chart = QChart()
        series = QPieSeries()
        
        # 统计数据
        total_files = task['total_files']
        passed_files = sum(1 for r in task['results'].values() if r['status'] == 'success')
        failed_files = sum(1 for r in task['results'].values() if r['status'] == 'failed')
        filtered_files = total_files - passed_files - failed_files
        

        # 添加数据
        if passed_files:
            series.append(f"通过 ({passed_files})", passed_files)
        if filtered_files:
            series.append(f"未通过 ({filtered_files})", filtered_files)
        if failed_files:
            series.append(f"失败 ({failed_files})", failed_files)
        
        chart.addSeries(series)
        chart.setTitle("处理结果分布")
        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignRight)
        
        return chart

    @staticmethod
    def create_reasons_chart(task):
        """创建原因统计图"""
        chart = QChart()
        series = QBarSeries()
        
        # 统计原因
        reason_counts = {}
        for result in task['results'].values():
            for reason in result['filter_reasons']:
                reason_counts[reason['code']] = reason_counts.get(reason['code'], 0) + 1

        
        # 创建数据集
        bar_set = QBarSet("数量")
        categories = []
        for code, count in sorted(reason_counts.items(), key=lambda x: x[1], reverse=True):
            bar_set.append(count)
            categories.append(code)
        
        series.append(bar_set)
        chart.addSeries(series)
        
        # 设置坐标轴
        axis_x = QBarCategoryAxis()
        axis_x.append(categories)
        chart.addAxis(axis_x, Qt.AlignBottom)
        series.attachAxis(axis_x)
        
        axis_y = QValueAxis()
        chart.addAxis(axis_y, Qt.AlignLeft)
        series.attachAxis(axis_y)
        
        chart.setTitle("过滤原因分布")
        chart.legend().setVisible(False)
        
        return chart 